package com.alliky.core.base

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.alliky.common.entity.MessageEvent
import com.alliky.core.R
import com.gyf.immersionbar.ImmersionBar
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BasicActivity : AppCompatActivity() {

    abstract fun setLayout(): Any?

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (setLayout() is Int) {
            setContentView(setLayout() as Int)
        } else if (setLayout() is View) {
            setContentView(setLayout() as View?)
        } else {
            throw ClassCastException("type of setLayout() must be int or View!")
        }
        if (useEventBus()) {
            initEventBus()
        }

        setStatusBar()

        initView()
        initData()
    }

    open fun setStatusBar() {
        ImmersionBar.with(this).statusBarColor(R.color.deepskyblue).fitsSystemWindows(true)
            .statusBarDarkFont(false).init()
    }

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 初始化 View
     */
    abstract fun initView()

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(message: MessageEvent?) {
    }

    open fun initEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus()) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this)
            }
        }
    }
}